package com.weasing.res.web.action;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.weasing.res.dao.IWxUserdetailDao;
import com.weasing.res.domain.WxAnswer;
import com.weasing.res.domain.WxEvalrecord;
import com.weasing.res.domain.WxEvalresult;
import com.weasing.res.domain.WxFamilyinfo;
import com.weasing.res.domain.WxGendocresult;
import com.weasing.res.domain.WxGensugresult;
import com.weasing.res.domain.WxQgrouplist;
import com.weasing.res.domain.WxQuestion;
import com.weasing.res.domain.WxUserdetail;
import com.weasing.res.domain.WxUserlist;
import com.weasing.res.service.IWxAnswerService;
import com.weasing.res.service.IWxDictService;
import com.weasing.res.service.IWxEvalrecordService;
import com.weasing.res.service.IWxEvalresultService;
import com.weasing.res.service.IWxFamilyinfoService;
import com.weasing.res.service.IWxGendocresultService;
import com.weasing.res.service.IWxGensugresultService;
import com.weasing.res.service.IWxQgrouplistService;
import com.weasing.res.service.IWxQuestionService;
import com.weasing.res.service.IWxUserdetailService;
import com.weasing.res.service.IWxUserlistService;
import com.weasing.res.utils.RESUtils;
import com.weasing.res.utils.StringUtil;
import com.weasing.res.vo.WxQgroupVO;
import com.weasing.res.vo.WxQuestionVO;
import com.weasing.res.vo.WxUserdetailVO;
import com.weasing.res.web.action.base.BaseAction;

import net.sf.json.JSONObject;

@Controller
@Scope("prototype")
public class WxUserdetailAction extends BaseAction<WxUserdetail> {
	@Autowired
	private IWxUserdetailService wxUserdetailService;
	@Autowired
	private IWxDictService wxDictService;
	@Autowired
	private IWxQgrouplistService wxQgrouplistService;
	@Autowired
	private IWxQuestionService wxQuestionService;
	@Autowired
	private IWxUserlistService wxUserlistService;
	@Autowired
	private IWxFamilyinfoService wxFamilyinfoService;
	@Autowired
	private IWxEvalresultService wxEvalresultService;
	@Autowired
	private IWxEvalrecordService wxEvalrecordService;
	@Autowired
	private IWxGendocresultService wxGendocresultService;
	@Autowired
	private IWxGensugresultService wxGensugresultService;
	@Autowired
	private IWxAnswerService wxAnswerService;
	@Autowired
	private IWxUserdetailDao wxUserdetailDao;

	// 查询条件
	private String chargetypeStr;
	private String chargenameStr;
	private String totalscoreStr;
	// 查询展示list
	private List list;
	/**
	 * 查询的map
	 */
	private Map map = new HashMap();
	// 添加封装对象
	private WxUserdetail wxUserdetail;
	private WxUserlist wxUserlist;
	private WxEvalresult wxEvalresult;
	private List<WxFamilyinfo> wxFamilyinfoList;
	private WxEvalrecord wxEvalrecord;
	private WxGendocresult wxGendocresult;
	private WxGensugresult wxGensugresult;
	
	private List<WxQgroupVO> wxQgroupVOList;//每组规则得分小计
	private int countScore;//总分
	
	//封装家庭成员属性数组
	private String[] familytypes;
	private String[] ages;
	private String[] healthtypes;
	private String[] hasattends;
	private String[] hasotherattends;
        private String[] grouplist;
        private String[] scorelist;

	public String list() {

		// 查询获取犯罪类型
		List<String> chargetypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("chargetype"));
		RESUtils.getSession().setAttribute("chargetypes", chargetypes);
		list = wxUserdetailService.findAll();
		return "list";
	}

	/**
	 * 新的 查询所有的方法 集合 模糊查询 字段查询 非模糊查询于一身的 完结版本 字段类型任意 字段个数任意
	 * 
	 * @version 2.0
	 * @author 黄龙
	 * @return
	 */
	public String newFindlist() {
		// totalscoreStr：1表示羁押，总分小于0；-1表示不羁押，总分大于等于0；0表示全部
		List<String> chargetypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("chargetype"));
		RESUtils.getSession().setAttribute("chargetypes", chargetypes);
		// 以下是分页代码
		map.clear();
		if (StringUtil.isNotNulls(chargetypeStr)) {
			map.put("chargetype", Integer.valueOf(chargetypeStr));
		}
		if (StringUtil.isNotNulls(chargenameStr)) {
			map.put("chargename", chargenameStr);
		}
		// if (StringUtil.isNotNulls(totalscoreStr)) {
		// map.put("totalscore", chargenameStr);
		// }
		
		String parameter = RESUtils.getRequest().getParameter("currentPage");
		if (StringUtil.isNotNulls(parameter)) {
			pageBean.setCurrentPage(Integer.valueOf(parameter));
		}
		wxUserdetailService.newFindAll(pageBean, map);
		List<WxUserdetail> rows = pageBean.getRows();
		list = rows;
		RESUtils.getRequest().setAttribute("pageBean", pageBean);
		return "list";
	}

	public String find() {

		List<String> chargetypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("chargetype"));
		RESUtils.getSession().setAttribute("chargetypes", chargetypes);
		// totalscoreStr：1表示羁押，总分小于0；-1表示不羁押，总分大于等于0；0表示全部
		list = wxUserdetailService.findWxUserdetailByCondition(
				Integer.parseInt(chargetypeStr), chargenameStr,
				totalscoreStr);
		RESUtils.getSession().setAttribute("chargetypeStr", chargetypeStr);
		RESUtils.getSession().setAttribute("chargenameStr", chargenameStr);
		RESUtils.getSession().setAttribute("totalscoreStr", totalscoreStr);
		return "list";
	}

	/**
	 * 删除评估信息
	 * 
	 * @return
	 * 
	 */
	public void deleteWxUserdetail() {
		// 0位删除失败或者有关联 1为删除成功
		String parameter = RESUtils.getRequest().getParameter("usertailid");
		Integer usertailid = Integer.valueOf(parameter);
		try {
			wxUserdetailDao.delete(wxUserdetailDao.findById(usertailid));
			RESUtils.print("1");
		} catch (Exception e) {
			RESUtils.print("0");
		}
	}

	public String toAdd() {
		// 增加 新增评估 下拉信息-----begin
		// 查询获取犯罪类型
		List<String> chargetypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("chargetype"));
		RESUtils.getSession().setAttribute("chargetypes", chargetypes);
		// 是否共同犯罪
		List<String> isjointcrimes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("isjointcrime"));
		RESUtils.getSession().setAttribute("isjointcrimes", isjointcrimes);
		// 是否初犯
		List<String> crimetypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("crimetype"));
		RESUtils.getSession().setAttribute("crimetypes", crimetypes);
		// 证件类型
		List<String> credtypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("credtype"));
		RESUtils.getSession().setAttribute("credtypes", credtypes);
		// 民族
		List<String> nations = StringUtil.String2List(wxDictService
				.findWxDictByDictName("nation"));
		RESUtils.getSession().setAttribute("nations", nations);
		// 省
		// 市
		// 区
		// 婚姻状况
		List<String> marriagetypes = StringUtil.String2List(wxDictService
				.findWxDictByDictName("marriagetype"));
		RESUtils.getSession().setAttribute("marriagetypes", marriagetypes);
		// 与家庭成员关系
		List<String> familytypes2 = StringUtil.String2List(wxDictService
				.findWxDictByDictName("familytype"));
		RESUtils.getSession().setAttribute("familytypes", familytypes2);
		// 增加 新增评估 下拉信息-----end
		// 增加 评估问题列表信息-----begin
		findWxQuestionList();
                
		// 增加 评估问题列表信息-----end
		
		return "add";
	}
	//增加 评估问题列表信息,不包含答案分值
	private void findWxQuestionList(){
                //首先获取规则列表
                List<WxQgrouplist> grouplist = wxQgrouplistService.findAll();//分组列表
                //规则列表中对应包含questionllist(questionlist中每一项是question本身)
                
                if (grouplist.size() > 0) {
                    //WxQuestionVO
                    for (int i = 0; i < grouplist.size(); i++) {
                        List<WxQuestionVO> questionlist = new ArrayList<WxQuestionVO>();
                        List<WxQuestion> wqList = (List<WxQuestion>) wxQuestionService.findWxQuestionByQid(grouplist.get(i).getId());
                        if (wqList.size() > 0) {
                            for (int j = 0; j < wqList.size(); j++) {
                                WxQuestionVO questionitem=new WxQuestionVO();
                                questionitem.setWxQuestion(wqList.get(j));
                                List<WxAnswer> answerlist=(List<WxAnswer>) wxAnswerService.findWxAnswerByQid(wqList.get(j).getId());
                                questionitem.setWxAnswerList(answerlist);
                                questionitem.setAnswernum(answerlist.size());
                                questionlist.add(questionitem);
                            }
                            
                        }
                        grouplist.get(i).setQuestionlist(questionlist);
                    }
                    
                }
                
		RESUtils.getSession().setAttribute("wqlVOList", grouplist);
	}
	
	/*
	 * 计算评估分值
	 */
	public String calculateScore(){
		Map<String,Object> map = new HashMap<String, Object>();
		HttpServletRequest request = RESUtils.getRequest();
		String[] ids = request.getParameterValues("ids");
		String[] qgids = request.getParameterValues("qgids");
		
		wxQgroupVOList = new ArrayList<WxQgroupVO>();
		int[] aids = new int[ids.length];
		int[] ascores = new int[ids.length];
		
		//查询所有分组
		List<WxQgrouplist> wqls = wxQgrouplistService.findAll();
		for (int k = 0; k < wqls.size(); k++) {
			WxQgroupVO wqVO = new WxQgroupVO();
			wqVO.setWxQgrouplist(wqls.get(k));
			wqVO.setWxQgrouplistScore(0);
			for (int i = 0; i < ids.length; i++) {
				if(wqls.get(k).getId().equals(Integer.parseInt(qgids[i]==""?"0":qgids[i]))){
					List<WxAnswer> was = new ArrayList<WxAnswer>();
					//查询选择分组
					//WxQgrouplist wql = wxQgrouplistService.findById(Integer.parseInt(qgids[i]));
					//wqVO.setWxQgrouplist(wql);
					//计算分组评分小计
					int count=0;
					was = wxAnswerService.findWxAnswerByQid(Integer.parseInt(ids[i]));
					for (int j = 0; j < was.size(); j++) {
						if("是".equals(was.get(j).getAcontent())){
							count+=was.get(j).getScore();
							aids[i]=was.get(j).getId();
							ascores[i]=was.get(j).getScore();
						}
					}
					wqVO.setWxQgrouplistScore(count);
					//计算总分
					countScore+=count;
				}
			}
			wxQgroupVOList.add(wqVO);
		}
		RESUtils.getSession().setAttribute("ids", ids);
		RESUtils.getSession().setAttribute("qgids", qgids);
		RESUtils.getSession().setAttribute("aids", aids);
		RESUtils.getSession().setAttribute("ascores", ascores);
		RESUtils.getSession().setAttribute("countScore", countScore);
		
		try {
			map.put("success", "success");
			map.put("wxQgroupVOList", wxQgroupVOList);
			map.put("countScore", countScore);
			JSONObject json = JSONObject.fromObject(map);
			ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
			RESUtils.print(json.toString());
		} catch (Exception e) {
			
			map.put("success", "fail");
			JSONObject json = JSONObject.fromObject(map);
			RESUtils.print(json.toString());
			e.printStackTrace();
		}
		return null;
	}

	public String add() {
		int wulid = 0;// 保存后返回的羁押人员id
		int wudid = 0;// 保存后返回的案件信息id
		int wesid = 0;// 保存后返回的评估结果id
                HttpServletRequest request = RESUtils.getRequest();
		// 人员信息
		if (wxUserlist.getId() == 0) {
			wxUserlist.setCreatetime(new Timestamp(System.currentTimeMillis()));
			wxUserlistService.addWxUserlist(wxUserlist);
		} else {
            wxUserlist.setCreatetime(new Timestamp(System.currentTimeMillis()));
			wxUserlistService.updateWxUserlist(wxUserlist);
		}
		wulid = wxUserlist.getId();
//                return "";
		// 案件信息
		if (wxUserdetail.getChargename() != null) {
			wxUserdetail.setCreatetime(new Timestamp(System.currentTimeMillis()));
			wxUserdetail.setUserid(wulid);
			wxUserdetailService.addWxUserdetail(wxUserdetail);
		}
		wudid = wxUserdetail.getId();
               
                String hasfamilytypes=(String) request.getParameter("hasfamilytypes");
                if("y".equals(hasfamilytypes)){
                    familytypes = request.getParameterValues("familytypes");
                    ages = request.getParameterValues("ages");
                    healthtypes = request.getParameterValues("healthtypes");
                    hasattends = request.getParameterValues("hasattends");
                    hasotherattends = request.getParameterValues("hasotherattends");
                    
                    if(familytypes.length>0){
			for (int i = 0; i < familytypes.length; i++) {
				if(Integer.parseInt(familytypes[i])==0){
					continue;
				}
				WxFamilyinfo wf = new WxFamilyinfo();
				wf.setCreatetime(new Timestamp(System.currentTimeMillis()));
				wf.setUserid(wulid);
				wf.setUdetailid(wudid);
				wf.setFamilytype(Integer.parseInt(familytypes[i]));
				if(!"".equals(ages[i])){
					wf.setAge(Integer.parseInt(ages[i]));
				}
				wf.setHealthtype(Short.parseShort(healthtypes[i]));
				wf.setHasattend(Short.parseShort(hasattends[i]));
				wf.setHasattend(Short.parseShort(hasotherattends[i]));
				wxFamilyinfoService.addWxFamilyinfo(wf);
			}
                    }
                }
                
		// 家庭情况

		/*if (wxFamilyinfoList.size() > 0) {
			for (int i = 0; i < wxFamilyinfoList.size(); i++) {
				if(wxFamilyinfoList.get(i).getAge()==null||wxFamilyinfoList.get(i).getAge()==0){
					continue;
				}
				wxFamilyinfoList.get(i).setCreatetime(new Timestamp(System.currentTimeMillis()));
				wxFamilyinfoList.get(i).setUserid(wulid);
				wxFamilyinfoList.get(i).setUdetailid(wudid);
				wxFamilyinfoService.addWxFamilyinfo(wxFamilyinfoList.get(i));
			}
		}*/

		// 评估结果
		wxEvalresult = new WxEvalresult();
		wxEvalresult.setCreatetime(new Timestamp(System.currentTimeMillis()));
		wxEvalresult.setUserid(wulid);
		wxEvalresult.setUdetailid(wudid);
                
		countScore=Integer.parseInt(request.getParameter("countScore"));
		wxEvalresult.setTotalscore(countScore);
		wxEvalresultService.addWxEvalresult(wxEvalresult);
		wesid = wxEvalresult.getId();
		
		//评估明细
//		String[] ids =  (String[]) RESUtils.getSession().getAttribute("ids");
//		String[] qgids = (String[]) RESUtils.getSession().getAttribute("qgids");
//		int[] aids = (int[]) RESUtils.getSession().getAttribute("aids");
//		int[] ascores = (int[]) RESUtils.getSession().getAttribute("ascores");
                
                if(request.getParameterValues("grouplist")!=null){
                    grouplist =  request.getParameterValues("grouplist");
                }
                if(request.getParameterValues("scorelist")!=null){
                    scorelist =  request.getParameterValues("scorelist");
                }
                if(grouplist.length>0&&scorelist.length>0){
                    for (int i = 0; i < grouplist.length; i++) {
                            if((!"".equals(grouplist[i]))){
                                    String[] asid=grouplist[i].split("_");
                                    String[] scores=scorelist[i].split("_");
                                    if(asid.length==3&&scores.length==3&&asid[0].equals(scores[0])&&asid[1].equals(scores[1])&&!"0".equals(asid[2])){
                                        wxEvalrecord = new WxEvalrecord();
                                        wxEvalrecord.setCreatetime(new Timestamp(System.currentTimeMillis()));
                                        wxEvalrecord.setUserid(wulid);
                                        wxEvalrecord.setUdetailid(wudid);
                                        wxEvalrecord.setEresultid(wesid);
                                        wxEvalrecord.setQgroupid(Integer.parseInt(asid[0]));
                                        wxEvalrecord.setQid(Integer.parseInt(asid[1]));
                                        wxEvalrecord.setAid(String.valueOf(asid[2]));
                                        wxEvalrecord.setScores(Short.parseShort(String.valueOf(scores[2])));
                                        wxEvalrecordService.addWxEvalrecord(wxEvalrecord);
                                    }
                            }
                    }
                }
		
		//生成文书记录
//		wxGendocresult = new WxGendocresult();
//		wxGendocresult.setCreatetime(new Timestamp(System.currentTimeMillis()));
//		wxGendocresult.setUserid(wulid);
//		wxGendocresult.setUdetailid(wudid);
//		wxGendocresult.setEresultid(wesid);
//		wxGendocresult.setDocname("审查批准逮捕评估报告");
//		wxGendocresult.setHasdownload(Short.parseShort("0"));
//		wxGendocresultService.addWxGendocresult(wxGendocresult);
		
		//生成逮捕评估意见记录
//		wxGensugresult = new WxGensugresult();
//		wxGensugresult.setCreatetime(new Timestamp(System.currentTimeMillis()));
//		wxGensugresult.setUserid(wulid);
//		wxGensugresult.setUdetailid(wudid);
//		wxGensugresult.setEresultid(wesid);
//		wxGensugresult.setDocname("批准/不批准逮捕决定书");
//		wxGensugresult.setHasdownload(Short.parseShort("0"));
//		wxGensugresultService.addWxGensugresult(wxGensugresult);
                Map<String,Object> map = new HashMap<String, Object>();
                Map<String,Object> datamap = new HashMap<String, Object>();
		try {
                        datamap.put("userid",wulid);
                        datamap.put("udetailid",wudid);
                        datamap.put("eresultid",wesid);
			map.put("success", "success");
			map.put("data", datamap);
			JSONObject json = JSONObject.fromObject(map);
			ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
			RESUtils.print(json.toString());
		} catch (Exception e) {
			map.put("success", "fail");
			JSONObject json = JSONObject.fromObject(map);
			RESUtils.print(json.toString());
			e.printStackTrace();
		}

		return null;
	}

	public String getChargetypeStr() {
		return chargetypeStr;
	}

	public void setChargetypeStr(String chargetypeStr) {
		this.chargetypeStr = chargetypeStr;
	}

	public String getChargenameStr() {
		return chargenameStr;
	}

	public void setChargenameStr(String chargenameStr) {
		this.chargenameStr = chargenameStr;
	}

	public String getTotalscoreStr() {
		return totalscoreStr;
	}

	public void setTotalscoreStr(String totalscoreStr) {
		this.totalscoreStr = totalscoreStr;
	}

	public List<WxUserdetailVO> getList() {
		return list;
	}

	public void setList(List<WxUserdetailVO> list) {
		this.list = list;
	}

	public WxUserdetail getWxUserdetail() {
		return wxUserdetail;
	}

	public void setWxUserdetail(WxUserdetail wxUserdetail) {
		this.wxUserdetail = wxUserdetail;
	}

	public WxUserlist getWxUserlist() {
		return wxUserlist;
	}

	public void setWxUserlist(WxUserlist wxUserlist) {
		this.wxUserlist = wxUserlist;
	}

	public WxEvalresult getWxEvalresult() {
		return wxEvalresult;
	}

	public void setWxEvalresult(WxEvalresult wxEvalresult) {
		this.wxEvalresult = wxEvalresult;
	}

	public List<WxFamilyinfo> getWxFamilyinfoList() {
		return wxFamilyinfoList;
	}

	public void setWxFamilyinfoList(List<WxFamilyinfo> wxFamilyinfoList) {
		this.wxFamilyinfoList = wxFamilyinfoList;
	}

	public WxEvalrecord getWxEvalrecord() {
		return wxEvalrecord;
	}

	public void setWxEvalrecord(WxEvalrecord wxEvalrecord) {
		this.wxEvalrecord = wxEvalrecord;
	}

	public WxGendocresult getWxGendocresult() {
		return wxGendocresult;
	}

	public void setWxGendocresult(WxGendocresult wxGendocresult) {
		this.wxGendocresult = wxGendocresult;
	}

	public WxGensugresult getWxGensugresult() {
		return wxGensugresult;
	}

	public void setWxGensugresult(WxGensugresult wxGensugresult) {
		this.wxGensugresult = wxGensugresult;
	}

	public List<WxQgroupVO> getWxQgroupVOList() {
		return wxQgroupVOList;
	}

	public void setWxQgroupVOList(List<WxQgroupVO> wxQgroupVOList) {
		this.wxQgroupVOList = wxQgroupVOList;
	}

	public int getCountScore() {
		return countScore;
	}

	public void setCountScore(int countScore) {
		this.countScore = countScore;
	}

	public String[] getFamilytypes() {
		return familytypes;
	}

	public void setFamilytypes(String[] familytypes) {
		this.familytypes = familytypes;
	}

	public String[] getAges() {
		return ages;
	}

	public void setAges(String[] ages) {
		this.ages = ages;
	}

	public String[] getHealthtypes() {
		return healthtypes;
	}

	public void setHealthtypes(String[] healthtypes) {
		this.healthtypes = healthtypes;
	}

	public String[] getHasattends() {
		return hasattends;
	}

	public void setHasattends(String[] hasattends) {
		this.hasattends = hasattends;
	}

	public String[] getHasotherattends() {
		return hasotherattends;
	}

	public void setHasotherattends(String[] hasotherattends) {
		this.hasotherattends = hasotherattends;
	}
	
}
